package com.topone.sms;

import com.topone.Exception.FanZoneServiceException;
import com.topone.dataObject.VerifyCode;
import com.topone.repository.VerifyCodeRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseSmsService implements SmsService {

    protected final Logger LOG = LoggerFactory.getLogger(this.getClass());

    protected long expiredTime;

    protected VerifyCodeRepository verifyCodeRepository;

    @Autowired
    public void setVerifyCodeRepository(VerifyCodeRepository verifyCodeRepository) {
        this.verifyCodeRepository = verifyCodeRepository;
    }

    @Override
    public void checkSmsCode(String mobile, String code) {
        if (StringUtils.isEmpty(code)) {
            throw new FanZoneServiceException("验证码不能为空");
        }
        VerifyCode verifyCode = verifyCodeRepository.getOne(mobile);
        if (verifyCode == null) {
            throw new FanZoneServiceException("无效的验证码或手机号码");
        }
        if (!verifyCode.getCode().equals(code)) {
            throw new FanZoneServiceException("验证码无效");
        }
        if ((verifyCode.getGeneratedTime() + expiredTime) < System.currentTimeMillis()) {
            throw new FanZoneServiceException("验证码过期");
        }
    }

}
